package com.example.medicinetime;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private RecyclerView record_rv;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas();
        try {
            checkAlarm();
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        for(MedicienRecord medicienRecord : dbManager.listAll()){
//            MedicienRecord item = new MedicienRecord(rateItem.getCurName(),rateItem.getCurRate());
//            retList.add(item);
//        }
    }

    public void add_medicine(View view){
        Log.i(TAG, "add_medicine: ");
        Intent input = new Intent(this, InputActivity.class);//this当前activity对象
        startActivity(input);

    }

    private void initView() {
        record_rv = (RecyclerView) findViewById(R.id.medicien_recycler);
    }

    private List<MedicienRecord> loadRecord(){
        List<MedicienRecord> list=new ArrayList<>();

        DBManager dbManager2 = new DBManager(MainActivity.this);
//        dbManager.deleteAll();
        for(MedicienRecord medicienRecord : dbManager2.listAll()){
            MedicienRecord item = new MedicienRecord(medicienRecord.getId(),medicienRecord.getMedicienName(),medicienRecord.getStartTime(),medicienRecord.getDuration(),medicienRecord.getDailytime(),medicienRecord.getDosis(),medicienRecord.getAlarmId());
            list.add(item);
        }
        return list;
    }

    private void initDatas() {
        //添加数据
        List<MedicienRecord> list=loadRecord();

        Log.i(TAG, "initDatas: list="+list);
        //设置列表显示方式
        record_rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        //设置列表默认动画效果
        record_rv.setItemAnimator(new DefaultItemAnimator());
        //绑定适配器
        MyAdapter myAdapter=new MyAdapter(list);
        record_rv.setAdapter(myAdapter);
        //列表点击事件
        myAdapter.setOnItemClickLitener(new MyAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.i("position=",position+"");
                //点击暂停音乐
                if(AlarmReceiver.mediaPlayer.isPlaying()){
                    AlarmReceiver.mediaPlayer.stop();
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示")
                        .setMessage(R.string.make_sure_finash_tip)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.i(TAG, "onClick: 对话框事件处理");
                                DBManager dbManager2 = new DBManager(MainActivity.this);
                                MedicienRecord medicienRecord = list.get(position);
                                //添加记录到已完成服药表
                                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd" );
                                SimpleDateFormat sdf2 =   new SimpleDateFormat( "HH:mm" );
                                Date now = Calendar.getInstance().getTime();
                                FinishRecord finishRecord=new FinishRecord(medicienRecord.getMedicienName(),sdf.format(now),sdf2.format(now),medicienRecord.getDosis());
                                dbManager2.add_completed(finishRecord);

                                //根据不同duration判断点击事件
                                if(medicienRecord.getDuration()>1){
                                    medicienRecord.setDuration(medicienRecord.getDuration()-1);
                                    //startime向后推一天
                                    Calendar calendar = new GregorianCalendar();
                                    try {
                                        calendar.setTime(sdf.parse(medicienRecord.getStartTime()));
                                        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数往后推,负数往前移动
                                        Date updated_time=calendar.getTime(); //日期往后推1天的结果
                                        medicienRecord.setStartTime(sdf.format(updated_time));
                                        dbManager2.update(medicienRecord);//更新数据库内对应信息
                                        myAdapter.removeData(position);
                                        initDatas();
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                }else{
                                    int delete_num=medicienRecord.getId();
                                    Log.i(TAG, "onClick: delete_num="+delete_num);
                                    dbManager2.delete(delete_num);
                                    //取消闹钟
                                    Alarm.cancelAlarmTimer(MainActivity.this,"VIDEO_TIMER",list.get(position).getAlarmId());
                                    myAdapter.removeData(position);
                                    initDatas();
                                }
                            }
                        })
                        .setNegativeButton("否",null);
                builder.create().show();
            }
        });

    }

    //检查重复闹钟是否过期
    private void checkAlarm() throws ParseException {
        //获取数据
        DBManager dbManager = new DBManager(MainActivity.this);
        for(MedicienRecord medicienRecord : dbManager.listAll()){
            //判断duration
            if(medicienRecord.getDuration()>1){
                String record_time_str = medicienRecord.getStartTime()+" "+medicienRecord.getDailytime();
                Log.i(TAG, "checkAlarm: 日期往后推前record_time_str="+record_time_str);
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
                Date record_time = sdf.parse(record_time_str);
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(record_time);
                calendar.add(calendar.DATE,medicienRecord.getDuration()); //把日期往后增加一天,整数往后推,负数往前移动
                Date end_time=calendar.getTime(); //日期往后推duration天的结果
                Log.i(TAG, "checkAlarm: 日期往后推后end_time="+sdf.format(end_time));
                Date now = Calendar.getInstance().getTime();
                if(now.after(end_time)){
                    //已超过服药天数，取消重复闹钟
                    Alarm.cancelAlarmTimer(MainActivity.this,"VIDEO_TIMER",medicienRecord.getAlarmId());
                }
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.finished_menu){
            Intent completed_intent = new Intent(this,CompletedListActivity.class);
            startActivity(completed_intent);
            Log.i(TAG, "onOptionsItemSelected: 查看已服药记录");
        }
        return super.onOptionsItemSelected(item);
    }
}
